/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

Ext.QuickTips.init();
var _pageSize = 20;

var fieldName = ['id', 'code', 'name', 'shortName', 'linkMan', 'address', 'telphone', 'updateTime', 'createTime', 'status', 'orgCode', 'orgTypeId', 'orgTypeName', 'note'];
var fieldLabel = ['ID', '机构编码', '名称', '简称', '联系人', '地址', '电话', '更新时间', '创建时间状态', '状态', '上级单位', '单位类别ID', '单位类别', '备注'];
//var fieldType = [];

//var saveServlet = '../../servlet/system/OrgSave';
//var loadServlet = '../../servlet/system/OrgLoad';
//var deleteServlet = '../../servlet/system/OrgDel';

var saveServlet =basePath+ 'servlet/system/OrgSave';
var loadServlet =basePath +'servlet/system/OrgLoad';
var deleteServlet =basePath+ 'servlet/system/OrgDel';

var theme = '单位';

var _title = currentOrgName + theme + '管理';

/*var columns=[checkboxSel];
 var columnIndices = [];*/
var orgTypeStore = new Ext.data.JsonStore({//开始定义单位类型下拉框
    url: '../../servlet/common/SimpleFormInfoLoad',
    baseParams: {id: 'id', name: 'name', tableName: 't_orgType'},
    autoLoad: true,
    root: 'data',
    fields: ['id', 'name']
});

var orgTypeCombo = {
    xtype: 'combo',
    store: orgTypeStore,
    id: 'OrgTypeId',
    displayField: 'name',
    valueField: 'id',
    hiddenName: 'orgTypeId',
    typeAhead: true,
    editable: true,
    mode: 'remote',
    forceSelection: true,
    allowBlank: true,
    triggerAction: 'all',
    fieldLabel: '单位类别',
    emptyText: '请选择单位类型...',
    selectOnFocus: true
};

var inputForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'input-form',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [{
                    name: fieldName[0],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[0],
                    hidden: true
                }
                , {
                    name: 'code',
                    xtype: 'textfield',
                    fieldLabel: '机构编码',
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 50,
                    maxLengthText: '不能多于50个字符,1个汉字占用2个字符'
                }
                , {
                    name: 'name',
                    xtype: 'textfield',
                    fieldLabel: '名称',
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 50,
                    maxLengthText: '不能多于50个字符,1个汉字占用2个字符'
                }, {
                    name: 'shortName',
                    xtype: 'textfield',
                    fieldLabel: '简称',
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 50,
                    maxLengthText: '不能多于50个字符,1个汉字占用2个字符'
                }, orgTypeCombo, {
                    name: 'linkMan',
                    id: 'linkMan',
                    xtype: 'textfield',
                    fieldLabel: '联系人',
                    allowBlank: true,
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }, {
                    name: 'address',
                    xtype: 'textfield',
                    fieldLabel: '地址',
                    allowBlank: true,
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }, {
                    name: 'telphone',
                    xtype: 'textfield',
                    fieldLabel: '电话',
                    allowBlank: true,
                    regex: /^([0-9]+)$/,
                    regexText: "手机号码只能输入数字",
                    maxLength: 20,
                    maxLengthText: '不能多于20个字符,1个汉字占用2个字符'
                }, {
                    name: 'note',
                    xtype: 'textfield',
                    fieldLabel: '备注',
                    allowBlank: true,
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                //parent.Ext.getCmp('OrganTree').getRootNode().reload();
                                parent.Ext.getCmp('OrganTree').getNodeById(currentOrgCode).reload();
                                win.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime(); 
                        submitConfig.params.token=token;
                        submitConfig.params.token1=token1;
                        if (type === 1)
                            submitConfig.params.cmd = 'create';
                        else {
                            submitConfig.params.id = checkboxSel.getSelected().get("id");
                            submitConfig.params.cmd = 'update';
                        }
                        Ext.getCmp('input-form').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        win.hide();
                    }
                }]
        }
);
var win = new Ext.Window({
    layout: 'form',
    width: 340,
    autoHeight: true,
    closeAction: 'hide',
    items: [inputForm]
});
var type = 1;         //判断打开窗口是进行更新，还是新建。1-新建；2-修改
var updated = false;
function addnew() {
    if (win === null) {
        win = new Ext.Window({
            layout: 'form',
            width: 340,
            autoHeight: true,
            closeAction: 'hide',
            modal: true,
            items: [inputForm]
        });
    }
    type = 1;
    win.setTitle('增加' + theme);
    //if (updated)
    // Ext.getCmp('addusr-form').getForm().getEl().dom.reset();
    Ext.getCmp('input-form').getForm().reset();
    //Ext.getCmp('name').setValue(currentOrgName);
    win.show();
    //loginForm.form.reset();

    //Ext.getCmp('code').enable();    
}

function update() {
    updated = true;
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要选择一个记录才能修改");
    }
    else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("系统提示", "您选择了多个记录，只能选择一个记录进行修改");
    }
    else {
        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                closeAction: 'hide',
                modal: true,
                items: [inputForm]
            });
        }

        //alert(checkboxSel.getSelected().get('code'));
        type = 2;
        Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());        


        win.setTitle('修改' + theme);
        win.show();
        //Ext.getDom('win-title').innerHTML='修改监控设备信息';
    }
}

function remove() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能删除");
    }else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("系统提示", "您选择了多个记录，一次只能删除一个单位数据");
    }
    else {
        var msg;
        if(loadCmd === 'normal'){
            msg = "确实要删除所选的记录吗?";
        }else{
            msg="删除单位，将删除相关单位下的所有数据。包括监测点信息，日数据，月数据等等<br/>请谨慎操作！！！";
        }
        Ext.MessageBox.confirm('系统提示', msg, function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    if (i === 0)
                        jsonData = jsonData + ss;
                    else
                        jsonData = jsonData + "," + ss;
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteServlet, //提交的删除地址
                    params: {token:token,token1:token1,ids: jsonData},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("系统提示", "所选记录成功删除！");
                                store.reload(); //重新load数据   	
                                parent.Ext.getCmp('OrganTree').getNodeById(currentOrgCode).reload();
                            }
                            else {
                                Ext.Msg.alert('系统提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("系统提示", "所选记录删除失败！");
                        }
                    }
                });
            }
        });
    }
}

function restore() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能恢复");
    }
    else {
        Ext.MessageBox.confirm('提示', '确实要恢复所选的记录吗?', function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    if (i === 0)
                        jsonData = jsonData + ss;
                    else
                        jsonData = jsonData + "," + ss;
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: saveServlet, //提交的删除地址
                    params: {token:token,token1:token1,ids: jsonData,cmd:'restore'},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "所选记录成功恢复！");
                                store.reload(); //重新load数据   	
                                parent.Ext.getCmp('OrganTree').getNodeById(currentOrgCode).reload();
                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("提示", "所选记录恢复失败！");
                        }
                    }
                });
            }
        });
    }
}

var checkboxSel = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
var store;
function buildWindow() {


    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName
        , baseParams: {loadCmd:loadCmd,start: 0, limit: _pageSize}
        , autoLoad: true
    });

    var grid = new Ext.grid.GridPanel({
        title: _title,
        store: store,
        sm: checkboxSel,
        columns: [
            checkboxSel,
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0], hidden: true},
            {header: fieldLabel[1], width: 100, sortable: true, dataIndex: fieldName[1], hidden: true},
            {header: fieldLabel[2], width: 150, sortable: true, dataIndex: fieldName[2]},
            {header: fieldLabel[3], width: 80, sortable: true, dataIndex: fieldName[3]},
            {header: '单位类别', width: 80, sortable: true, dataIndex: 'orgTypeName'},
            {header: fieldLabel[4], width: 80, sortable: true, dataIndex: fieldName[4]},
            {header: fieldLabel[5], width: 200, sortable: true, dataIndex: fieldName[5]},
            {header: fieldLabel[6], width: 100, sortable: true, dataIndex: fieldName[6]},
            {header: fieldLabel[7], width: 80, sortable: true, dataIndex: fieldName[7], xtype: 'datecolumn', format: 'Y-m-d'},
            {header: fieldLabel[8], width: 100, sortable: true, dataIndex: fieldName[8], xtype: 'datecolumn', format: 'Y-m-d'},
            {header: '备注', width: 100, sortable: true, dataIndex: 'note'}
        ],
        //autoExpandColumn: fieldName[2],
        //renderTo: Ext.getBody(),
        //width: 780,
        //height: 590,
        loadMask: true,
        tbar: new Ext.Toolbar([
            {text: '新增', iconCls: 'icon-add', handler: addnew,hidden:loadCmd==='normal'?false:true},            
            {text: '修改', iconCls: 'icon-edit', handler: update,hidden:loadCmd==='normal'?false:true},            
            {text: '删除', iconCls: 'icon-delete', handler: remove},
            {text: '恢复', iconCls: 'icon-restore', handler: restore,hidden:loadCmd==='normal'?true:false}
        ]),
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: "目前没有" + theme + '信息'
        })
    });
    //grid.el.center();
    //store.load({params: {start: 0, limit: _pageSize}});

    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });
}
Ext.onReady(buildWindow);  